﻿using System;
using System.IO;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Application;
using Application.Dao;
using Ay.Framework.WPF.Controls;
using Event;
using org.diordna.eventbus;

namespace 小工具.Views.EditApplication
{
    /// <summary>
    /// _ViewStartView.xaml 
    /// 创建时间：2017/9/5 11:57:44
    /// </summary>
    public partial class EditApplicationView : AyWindow
    {

        private CApplication app;
        private bool IsFirst = false;

        public EditApplicationView(CApplication app)
        {
            InitializeComponent();
            Init(app);
        }
        public EditApplicationView(CApplication app, bool IsFirst)
        {
            InitializeComponent();
            this.IsFirst = IsFirst;
            Init(app);
        }

        private void Init(CApplication app)
        {
            this.app = app;

            AppName.Text = app.Name;
            AppPath.Text = app.Path;
            AppArgu.Text = app.Argument;
            
            BitmapImage img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri(GetAppImagePath(app), UriKind.RelativeOrAbsolute);
            img.EndInit();
            img.Freeze();
            AppIcon.Source = img;
        }

        private string GetAppImagePath(CApplication app)
        {
            string path = Path.GetFullPath(@".\img\app\" + app.Guid + ".png");
            FileInfo info = new FileInfo(path);
            if (!info.Directory.Exists)
            {
                info.Directory.Create();
            }

            return path;
        }

        private void MoveWindow(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void Confirm_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!(AppName.Text.Equals(app.Name) && AppArgu.Text.Equals(app.Argument)) || IsFirst)
            {
                app.Name = AppName.Text;
                app.Argument = AppArgu.Text;
                if (!IsFirst)
                {
                    new AppDao().Update(app);
                } else
                {
                    new AppDao().Insert(app);
                }
                EventBus.Instance.Publish(new BaseEvent(MainViewEvent.NOTIFY_APP_INIT));
            }
            Close();
        }
    }
}
